<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <div id="btns">
        <button data-path="news">新闻</button>
        <button data-path="play">娱乐</button>
        <button data-path="music">音乐</button>
      </div>
      <div id="view"></div>
    </div>
    <script>
      const oBtns = document.querySelectorAll("#btns button");
      const oViews = document.querySelector("#view");

      //路由表
      const routes = [
        { path: "/news", content: "我是新闻组件" },
        { path: "/play", content: "我是娱乐组件" },
        { path: "/music", content: "我是音乐组件" },
      ];

      //1.点击按钮改变hash地址
      for (var i = 0; i < oBtns.length; i++) {
        oBtns[i].onclick = function () {
          location.hash = this.dataset.path;
        };
      }

      //2.监听hash的变化,然后根据和路由表的对比,切换view中的内容
      window.onhashchange = function (e) {
        // console.log(e.newURL.split("#")[1]);
        const nowHash = e.newURL.split("#")[1];
        routes.forEach((item) => {
          if (item.path.split("/")[1] === nowHash) {
            oViews.textContent = item.content;
          }
        });
      };
    </script>
  </body>
</html>